//本js中调用日期的function都在common/js/dateUtil.js中
AnalysisQcTrend = {
	analysisDicChart : null,
	analysisDicTable : null
	
};

$(function () {
	//患者类型
    $('#dateRange').combobox({
    	data:[
    	      {value:"0",text:"在院患者"},
    	      {value:"1",text:"出院患者"}
    	      ],
        valueField:'value',
        textField:'text',
        onSelect:AnalysisQcTrend.dateRangeChange,
        onLoadSuccess:function () {
        	$(this).combobox("setValue", "0");
        }
    });
    //病种
    $('#entityType').combobox({
        data:$.parseJSON($("#entityMap").val()),
        valueField:'value',
        textField:'text',
        defaultFilter: 6
    });
	//统计粒度
	$('#analysisGrain').combobox({
		data:[
		      {value:"0",text:"天"},
		      {value:"1",text:"周"},
		      {value:"2",text:"月"},
		      {value:"3",text:"年"}
		      ],
	    valueField:'value',
	    textField:'text',
	    onLoadSuccess:function () {
	    	$(this).combobox("setValue", "2");
	    }
	});
	//科室
	$('#depart').combobox({
		data:$.parseJSON($("#departMap").val()),
	    valueField:'value',
	    textField:'text',
		onSelect:AnalysisQcTrend.medicalGroupChange
	});
	//院区
	$('#office').combobox({
		data:$.parseJSON($("#officeMap").val()),
	    valueField:'value',
	    textField:'text',
	    onSelect:AnalysisQcTrend.officeChange,
	    onLoadSuccess: function () {
			var hospId = $('#hospitalId').val();
			if (hospId != "") {
				$(this).combobox("setValue", hospId);
				$(this).combobox('disable');
			} else {
				//加载完成后,val[0]写死设置选中第一项
				var val = $(this).combobox("getData");
				if (val.length == 2) {//如果就一个院区 加上全部=2
					$(this).combobox("setValue", val[1].value);
					AnalysisQcTrend.officeChange(val[1]);
					$("#oneOffice").val("yes");
				} else {
					$(this).combobox("setValue", "");
					$("#oneOffice").val("no");
				}
			}
        }
	});
	
	$('#startDate').datebox('setValue',getLast2YearToday());
	$('#endDate').datebox('setValue',getCurrentDate());
	
	//查询指标配置
	var ajax = new $ax(Sys.backendPath + "/analysis/qcportal/getQcTrendDic", function(data){
        AnalysisQcTrend.analysisDicChart = data.chart;
		var tableDic = {};
		$.each(data.table,function(index,dic){
			tableDic[dic.analysisKey2] = dic.analysisStatus==1?true:false;
		});
        AnalysisQcTrend.analysisDicTable = tableDic;
    },function(data){
    	layer.msg("查询失败!", {icon: 2});
    });
    ajax.setAsync(false);
    ajax.start();
    
    
	//查询加载表格的数据
    AnalysisQcTrend.initChartTable();
});

AnalysisQcTrend.officeChange = function(that){
    var ajax = new $ax(Sys.backendPath + "/sds/common/deptListByHospId", function(data){
        $('#depart').combobox({
            data:data,
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
			onSelect:AnalysisQcTrend.medicalGroupChange,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                $(this).combobox("setValue", "");
				AnalysisQcTrend.medicalGroupChange(this)
            }
        });
    },function(data){
        layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
    });
    ajax.set({"hospID":that.value,"id":"depart"});
    ajax.start();
}

/**
 * 切换科室，查询下属医疗组
 */
AnalysisQcTrend.medicalGroupChange = function(that){
	var ajax = new $ax(Sys.backendPath + "/sds/common/groupListByDeptId", function(data){
		$('#medicalGroup').combobox({
			data:data,
			valueField:'value',
			textField:'text',
			defaultFilter: 6,
			onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
				$(this).combobox("setValue", "");
			}
		});
	},function(data){
		layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
	});
	ajax.set({"deptId":that.value,"id":"medicalGroup"});
	ajax.start();
}
/**
 * 查询图和表数据
 */
AnalysisQcTrend.initChartTable = function(){
	var params = {};
	var ajax = new $ax(Sys.backendPath + "/analysis/qcportal/selectQcTrendData", function (data) {
        AnalysisQcTrend.drawChart(data.chartDatas);
		$('#analysisTable').bootstrapTable("destroy");//先销毁原来的表格
        AnalysisQcTrend.drawTable(data.tableDates);
    }, function (data) {
    });
	params.dateRange = $('#dateRange').datebox('getValue');//患者类型
	params.startDate = $('#startDate').datebox('getValue')+" 00:00:00";//开始日期
	params.endDate = $('#endDate').datebox('getValue')+" 23:59:59";//开始日期
	params.analysisGrain = $('#analysisGrain').combobox('getValue');//统计粒度
	params.analysisDesc = $('#analysisDesc').val();//分析类型 全院或科室
	params.office = $("#office").combobox("getValue");
	params.depart = $("#depart").combobox("getValue");
	params.medicalGroup = $("#medicalGroup").combobox("getValue");
	params.oneOffice = $("#oneOffice").val();
	params.entityType = $("#entityType").combobox("getValue");
	params.doctor = $("#doctor").val();
	params.day = "day";
	// params.tableYear = tableYear;
	ajax.set(params);
    ajax.start();
};

/**
 * 根据数据画图
 */
AnalysisQcTrend.drawChart = function(chartDatas){
	echarts.init($("#analysisChart")[0]).dispose();
	var lines = [];
	var chartDic = AnalysisQcTrend.analysisDicChart;
	$.each(chartDic,function(index,dic){
		lines.push({desc:dic.analysisName,data:[],code:dic.analysisKey});
	});
	var chartParams = {
			backgroundColor : '#f2f2f2',//背景颜色
			isHorizontal : false,
			yAxisName : '数量',//y轴单位
			formatterFunc : function(params){
				var backStr = "";
				var relVal = params[0].name;
				backStr += relVal + "<br>";
				for (var i = 0;i < params.length; i++) {
					backStr += params[i].marker+params[i].seriesName + "：" +params[i].value+ "%<br>";
				}
				return backStr;
			},
			titleShow:false,
			isDataZoom:false,//是否显示缩放
			legendShow : true,
			legendPosition : 'top',
			gridLeft:"20px",
			gridRight:"10px",
			gridTop:"30px",
			gridBottom:"5px",
			rotate:0,//x轴数据偏移角度
			showLabel : true,
			legend:{
				show : false
			}
		};
	lineChartVte($("#analysisChart"), lines, chartDatas,null,null,chartParams);
};
/**
 * 根据数据画表
 */
AnalysisQcTrend.drawTable = function(tableDates){
	this.$table = 
		$('#analysisTable').bootstrapTable({
		data:tableDates,

		striped: false,//是否显示行间隔色
		pagination: false,//是否显示分页
		showFooter: true,
		//paginationLoop: false,
		//pageSize : 5,//用于设置每页初始显示的条数
		//pageList :[4],
		//sidePagination: 'server',//设置在哪进行分页，默认”client”，可选”server”,返回数据模板不同
		sortName: "disDate",
        sortOrder: 'desc',// desc  asc 
		maintainSelected: true,//设为true 为选中的状态
		cache: false,
		search:false, //搜索框
		columns: [
					{title: '入/出院日期', field: 'firstDate', align: 'center', valign: 'middle', sortable: true,
						footerFormatter:function(value){
							return "总计";
						}
					},
					{title: '患者总数', field: 'caseNum', align: 'center', valign: 'middle', sortable: true,
						footerFormatter:function(value){
							return AnalysisQcTrend.sumFieldValue(value,"caseNum");
						}
					},
					{title: '入组病种数', field: 'entityNum', align: 'center', valign: 'middle', sortable: true,
						footerFormatter:function(value){
							return AnalysisQcTrend.sumFieldValue(value,"entityNum");
						}
					},
					{title: '触发质控病种数', field: 'entityNumTri', align: 'center', valign: 'middle', sortable: true,
						footerFormatter:function(value){
							return AnalysisQcTrend.sumFieldValue(value,"entityNumTri");
						}
					},

					{title: '触发质控项患者例数', field: 'qcCase', align: 'center', valign: 'middle', sortable: true,
                        formatter:function(value,row,index){
							if(row.qcCase >0){
                                return "<a title='详细' onclick='openCaseDetail(&apos;"+row.firstDate+"&apos;)'>"+value+"</a>";
							}else{
								return 0;
							}

                        },
						footerFormatter:function(value){
							return AnalysisQcTrend.sumFieldValue(value,"qcCase");
						}
					},
					{title: '触发质控人次数', field: 'qcTri', align: 'center', valign: 'middle', sortable: true,
						footerFormatter:function(value){
							return AnalysisQcTrend.sumFieldValue(value,"qcTri");
						}
					},
					{title: '患者所在科室数', field: 'deptNum', align: 'center', valign: 'middle', sortable: true,
						footerFormatter:function(value){
							return AnalysisQcTrend.sumFieldValue(value,"deptNum");
						}
					},
					{title: '质控触发科室数', field: 'deptNumTri', align: 'center', valign: 'middle', sortable: true,
						footerFormatter:function(value){
							return AnalysisQcTrend.sumFieldValue(value,"deptNumTri");
						}
					}
                    ],
		onPostHeader: function(){  //当<thead></thead>中的内容被加载完后或者在你所用的DOM中有定义则被触发
			//$(".th-inner").css("font-weight","700");//表头字体加粗
			$("#analysisTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
        		$(this).attr("title",$(this).text());
        	});
        }
	});
};


/**
 * 导出表格数据
 */
AnalysisQcTrend.exportTable = function() {
    var dateType ="";
	if($('#dateRange').datebox('getValue') == 0){
        dateType="在院患者";
	}else{
        dateType="出院患者";
	}
	$("#analysisTableHead,#analysisTable,.fixed-table-footer>table").tableExport(
		{   
			type : 'xlsx',
			escape : 'false'
		},dateType+$('#startDate').datebox('getValue').replace(/-/g,"")+"～"+$('#endDate').datebox('getValue').replace(/-/g,"")+'过程质控趋势分析'
	)
	
};

/**
 * 计算表格最后一列数据和
 */
AnalysisQcTrend.sumFieldValue = function(value,field){
	
	var disSum = 0;
	var count = 0;
	for(var i in value){
		count += value[i][field];
	}
	if(count==0){//如果是0返回空
		return "";
	}
	var pre = (count/disSum * 100).toFixed(2);
	return count;
};
/**
 * 查询按钮
 */
AnalysisQcTrend.search = function(){
    AnalysisQcTrend.initChartTable();
};
/**
 * 日期范围改变时调用
 */
AnalysisQcTrend.dateRangeChange = function(that){
	if(that.value == 0){
		$("#startDateTitle").html("(入院)");
		$("#endDateTitle").html("(入院)");
	}else{
        $("#startDateTitle").html("(出院)");
        $("#endDateTitle").html("(出院)");
	}
}
function openCaseDetail(date){
    var index = layer.open({
        type: 2,
        title: ['<i class = "fa fa-line-chart"></i>&nbsp;触发质控项患者详细数据','padding-left:20px'],
        area: ['1300px', '500px'], //宽高
        fix: false, //不固定
        //maxmin: true,
        content: '/analysis/qcportal/to_QcCaseDetail?date='+date+'&dateRange='+$("#dateRange").datebox('getValue')+'&startDate='+$("#startDate").datebox('getValue')+
			'&endDate='+$('#endDate').datebox('getValue')+'&depart='+$("#depart").combobox("getValue")+'&office='+$("#office").combobox("getValue")+
			'&entityType='+$("#entityType").combobox("getValue")+'&doctor='+$("#doctor").val()+'&medicalGroup='+$("#medicalGroup").combobox("getValue")
    });
}